package com.mmall.commons;

import com.google.common.cache.CacheBuilder;
import com.google.common.cache.CacheLoader;
import com.google.common.cache.LoadingCache;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;

/**
 * @author wgt
 * @date 2018/6/25
 * @project mmall-server
 */
public class TokenCache {

    private static Logger logger = LoggerFactory.getLogger(TokenCache.class);

    public static final String TOKEN_PREFIX = "token_";

    /**
     * Guava 本地缓存池
     */
    private static LoadingCache<String, String> localCache
            = CacheBuilder.newBuilder()
            .initialCapacity(1000)
            .maximumSize(10000)
            .expireAfterAccess(1, TimeUnit.HOURS)
            .build(new CacheLoader<String, String>() {
                @Override
                public String load(String s) throws Exception {
                    return StringUtils.EMPTY;
                }
            });


    public static void setKey(String key, String value){
        localCache.put(key, value);
    }


    public static String getValue(String key){
        try {
            String value = localCache.get(key);
            if (!StringUtils.EMPTY.equals(value)){
                return value;
            }
        } catch (ExecutionException e) {
            logger.error(e.getMessage(), e);
        }
        return null;
    }
}
